<template>
    <div class="label-select" ref="labelSelect">
        <Button
            v-if="!hideMain"
            class="label-select-button"
            v-bind="$attrs"
            :style="buttonStyle"
            @click="showDownList"
        >
            <slot></slot>
        </Button>
        <div @click="showDownList">
            <slot name="main"></slot>
        </div>
        <div
            v-if="!needRefresh && showList"
            class="label-select-down-container"
        >
            <Spin v-if="loading" fix></Spin>
            <ul class="label-select-down-list">
                <li
                    class="label-select-down-item label-select-down-item-null"
                    v-if="!labelList.length"
                >
                    {{
                        $t("global.common.nodata", { defaultValue: "暂无数据" })
                    }}
                </li>
                <li
                    :class="`label-select-down-item ${
                        item.active ? 'label-select-down-item-active' : ''
                    } ${
                        item.selected ? 'label-select-down-item-selected' : ''
                    }`"
                    v-for="(item, index) in labelList"
                    :key="item.id"
                >
                    <div
                        v-if="!isEdit"
                        class="label-select-down-item-label"
                        @click="handleSelect(index)"
                    >
                        <span
                            :class="`color-cube color-${item.labelColour}`"
                        ></span>
                        <Tooltip :delay="1000" :content="item.labelName">
                            <span class="label-select-down-item-text">{{
                                item.labelName
                            }}</span>
                        </Tooltip>
                        <span
                            v-if="item.selected"
                            class="label-select-down-item-icon"
                        >
                            <Icon class="label-select" type="md-checkmark" />
                        </span>
                    </div>
                    <div v-else class="label-select-down-item-input">
                        <span
                            :class="`color-cube color-${item.labelColour}`"
                        ></span>
                        <Input
                            ref="input"
                            style="width: 80%"
                            clearable
                            v-model="item.labelName"
                            @input="itemInput(item)"
                            size="small"
                        />
                    </div>
                </li>
            </ul>
            <!-- <div v-show="!isEdit" class="label-select-down-menu">
                <Button type="primary" size="small" @click="addLabel">{{
                    $t("erp.b2corder.label_mark", { defaultValue: "标记" })
                }}</Button>
                <Button
                    class="margin-left-5"
                    type="default"
                    size="small"
                    @click="removeLabel"
                    >{{
                        $t("erp.b2corder.label_remove", {
                            defaultValue: "移除",
                        })
                    }}</Button
                >
                <Button
                    class="margin-left-5"
                    type="default"
                    @click="handleEdit"
                    size="small"
                    >{{
                        $t("global.common.operation_edit", {
                            defaultValue: "编辑",
                        })
                    }}</Button
                >
            </div> -->
            <div v-show="isEdit" class="label-select-down-menu">
                <Button size="small" type="primary" @click="handleSave">{{
                    $t("global.common.save", { defaultValue: "保存" })
                }}</Button>
                <Button
                    class="margin-left-5"
                    size="small"
                    type="default"
                    @click="handleCancel"
                    >{{
                        $t("global.common.operation_cancel", {
                            defaultValue: "取消",
                        })
                    }}</Button
                >
            </div>
        </div>
        <Modal class="modal-label-select" :width="260" v-model="showModal" :title="modalProps.title" @on-ok="confirmSelect" @on-visible-change="handleModalChange">
            <div class="label-select-modal-content">
                <Spin v-if="loading" fix></Spin>
                <ul class="label-select-down-list">
                    <li
                        class="
                            label-select-down-item label-select-down-item-null
                        "
                        v-if="!labelList.length"
                    >
                        {{
                            $t("global.common.nodata", {
                                defaultValue: "暂无数据",
                            })
                        }}
                    </li>
                    <li
                        :class="`label-select-down-item ${
                            item.active ? 'label-select-down-item-active' : ''
                        } ${
                            item.selected
                                ? 'label-select-down-item-selected'
                                : ''
                        }`"
                        v-for="(item, index) in labelList"
                        :key="item.id"
                    >
                        <div
                            class="label-select-down-item-label"
                            @click="handleSelect(index)"
                        >
                            <span
                                :class="`modal-color-cube color-${item.labelColour}`"
                            ></span>
                            <Tooltip :delay="500" :content="item.labelName">
                                <span class="label-select-down-item-text">{{
                                    item.labelName
                                }}</span>
                            </Tooltip>
                            <span
                                v-if="item.selected"
                                class="label-select-down-item-icon"
                            >
                                <Icon
                                    class="label-select"
                                    type="md-checkmark"
                                />
                            </span>
                        </div>
                    </li>
                </ul>
            </div>
            <!-- 列中使用
            <Button
                style="position: relative; top: -6px"
                type="primary"
                size="small"
                @click="confirmSelect"
                >确定</Button
            > -->
        </Modal>
    </div>
</template>

<script>
// import {
//     HttpGetAllLabel,
//     HttpSaveLabel
// } from "@mods/service/base";
export default {
    props: {
        hideMain: {
            type: Boolean,
            default: false,
        },
        // ajaxRequest: {
        //     type: Function,
        // },
        // module: {},
        dataList: {
            type: Array,
        },
        selected: {
            type: Array,
            default: () => {
                return [];
            },
        },
        needRefresh: {
            type: Boolean,
            default: false,
        },
        buttonStyle: {
            type: String
        },
        modalProps: {
            type: Object,
            default: () => {
                return {
                    title: ''
                }
            }
        }
    },
    watch: {
        dataList: {
            immediate: true,
            handler(val) {
                if (val && val.length) {
                    this.labelList = val.map((item) => {
                        return { ...item };
                    });
                    this.loading = false;
                }
            },
        },
        selected: {
            immediate: true,
            handler(val) {
                if (val && val.length) {
                    this.selectedArray = val;
                    this.hasUpdated = false;
                }
            },
        },
        showList: {
            immediate: true,
            handler(val) {
                if (val && this.needRefresh) {
                    console.log("showList", this.selectedArray);
                    this.selectedArray = this.selected;
                    this.handleSelectArray(true);
                }
            },
        },
    },
    data() {
        return {
            showList: false,
            isEdit: false,
            loading: true,
            labelList: [],
            changeMap: new Map(),
            selectedArray: [],
            hasUpdated: false,
            showModal: false
        };
    },
    mounted() {
        document.body.addEventListener("click", this.handleWindowClick, false);
        this.handleSelectArray();
    },
    updated() {
        this.handleSelectArray();
    },
    beforeUnmount() {
        document.body.removeEventListener(
            "click",
            this.handleWindowClick,
            false
        );
    },
    methods: {
        showDownList() {
            console.log(this.needRefresh, this.showList)
            if (!this.needRefresh) {
                this.showList = !this.showList;
            }
            else {
                this.showModal = true;
            }
        },
        handleModalChange (value) {
            console.log('modal', value);
            if (!value) {
                this.reset();
            }
            else {
                this.handleSelectArray(true);
            }
        },
        handleCancel() {
            this.isEdit = false;
            this.labelList = this.dataList.map((item) => {
                return {
                    ...item,
                };
            });
        },
        handleSelectArray(immediate = false) {
            if (!immediate && this.hasUpdated) return;
            // console.log("mounted", this.dataList, this.selectedArray);
            this.labelList = this.dataList.map((item) => {
                let nowItem = {
                    ...item,
                };
                this.selectedArray.forEach((selectedItem) => {
                    if (selectedItem.id === item.id) {
                        nowItem.selected = true;
                    }
                });
                return nowItem;
            });
            this.hasUpdated = true;
        },
        // async getLabel () {
        //     await HttpGetAllLabel({
        //         module: this.module || 26
        //     }).then(res => {
        //         console.log('labelData', res);
        //         this.dataList = res.data;
        //     }, err => {
        //         this.$Message.error(err);
        //     });
        //     this.loading = false;
        // },
        // async saveLabel () {
        //     await HttpSaveLabel({}).then();
        // },
        handleSave() {
            let flag = false;
            this.changeMap.forEach((value, key, map) => {
                console.log(value);
                if (!value.labelName) flag = true;
            });
            if (flag)
                return this.$Message.error(
                    this.$t("erp.b2corder.label_label_name_not_null", {
                        defaultValue: "标签名不能为空",
                    })
                );
            this.isEdit = false;
            this.$emit("on-change", "change", this.changeMap);
            this.changeMap = new Map();
        },
        itemInput(item) {
            console.log("change", item);
            this.changeMap.set(item.id, {
                labelId: item.labelId,
                labelName: item.labelName,
                labelColour: item.labelColour,
            });
        },
        reset() {
            this.showList = false;
            this.labelList.map((item) => {
                delete item.selected;
                delete item.active;
            });
        },
        confirmSelect() {
            let selected = [];
                // unSelected = [];
            console.log(this.selected);
            this.labelList.forEach((item) => {
                if (item.selected === true) {
                    selected.push(item.labelId);
                }
                // else {
                //     unSelected.push(item.labelId);
                // }
            });

            console.log('selected', selected);
            // let oldSelected = [];
            // this.selected.map(item => {
            //     oldSelected.push(item.labelId);
            // });
            // let needAddIds = selected, needRemoveIds = oldSelected;
            // console.log('needAddIds', needAddIds, 'needRemoveIds', needRemoveIds);
            // for (let i = 0; i < needRemoveIds.length; ) {
            //     let flag = false;
            //     for (let j = 0; j < needAddIds.length; ) {
            //         if (needRemoveIds[i] === needAddIds[j]) {
            //             flag = true;
            //             needRemoveIds.splice(i, 1);
            //             needAddIds.splice(j, 1);
            //             break;
            //         }
            //         j ++;
            //     }
            //     if (!flag) i ++;
            // }
            // console.log('needAddIds', needAddIds, 'needRemoveIds', needRemoveIds);
            // this.$emit("on-confirm-change", needAddIds, needRemoveIds);
            this.$emit('on-confirm-change', selected);
            this.reset();
        },
        addLabel() {
            let selected = this.labelList
                .filter((item) => {
                    return item.selected === true;
                })
                .map((item) => {
                    return item.labelId;
                });
            if (!selected.length)
                return this.$Message.warning(
                    this.$t("erp.b2corder.label_choose_label", {
                        defaultValue: "请先选中标签",
                    })
                );
            this.$emit("on-add", "add", selected);
            this.reset();
        },
        removeLabel() {
            let selected = this.labelList
                .filter((item) => {
                    return item.selected === true;
                })
                .map((item) => {
                    return item.labelId;
                });
            if (!selected.length)
                return this.$Message.warning(
                    this.$t("erp.b2corder.label_choose_label", {
                        defaultValue: "请先选中标签",
                    })
                );
            this.$emit("on-remove", "remove", selected);
            this.reset();
        },
        handleWindowClick() {
            // console.log('target', event.target);
            // console.log('targetParent', event.target.parentNode);
            // console.log('refs', this.$refs.labelSelect);
            // console.log('result', this.$refs.labelSelect.contains(event.target.parentNode) || this.$refs.labelSelect.contains(event.target) || event.target.parentNode === null);
            // console.log('event.target', event.target.className.indexOf('label-select'))
            if (
                event.target.className.indexOf("label-select") !== -1 ||
                this.$refs.labelSelect.contains(event.target.parentNode) ||
                this.$refs.labelSelect.contains(event.target) ||
                event.target.parentNode === null
            )
                return;
            // console.log('handleWindowClick');
            this.showList = false;
        },
        handleEdit() {
            this.isEdit = true;
            this.$nextTick(() => {
                this.$refs.input[0].focus();
            });
        },
        handleSelect(index) {
            // console.log('handleSelect', index)
            let item = this.labelList[index];
            this.$set(item, "selected", !this.labelList[index].selected);

            this.labelList.map((item) => {
                this.$set(item, "active", false);
            });
            this.$set(item, "active", true);
        },
    },
};
</script>
<style lang="scss" scoped>
.label-select {
    display: inline-block;
    position: relative;

    &-down-container {
        min-width: 200px;
        position: absolute;
        background-color: #fff;
        border-radius: 4px;
        box-shadow: 0 1px 6px rgba(0, 0, 0, 0.2);
        // border: 1px solid #ccc;
        top: 38px;
        left: 0;
        right: 0;
        z-index: 10;
    }
    &-down-list {
        padding: 5px 0;
        max-height: 270px;
        overflow: auto;
        word-break: break-all;
        white-space: nowrap;
    }
    &-down-item {
        color: #515a6e;

        &-text {
            display: inline-block;
            max-width: 140px;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        &-icon {
            flex: 1;
            text-align: right;
            padding-right: 10px;
        }

        &-label {
            display: flex;
            // justify-items: center;
            align-items: center;

            font-size: 14px;
            padding: 8px 0 8px 15px;
            transition: background 0.2s ease-in-out;
            &:hover {
                background-color: #f3f3f3;
            }
            cursor: pointer;
        }
        &-input {
            display: flex;
            align-items: center;

            font-size: 14px;
            padding: 8px 0 8px 15px;
            transition: background 0.2s ease-in-out;
            &:hover {
                background-color: #f3f3f3;
            }
            cursor: pointer;
        }
    }
    &-down-item-selected {
        color: rgba(45, 140, 240, 0.9);
    }
    &-down-item-active {
        background-color: #f3f3f3;
    }
    &-down-item-null {
        padding-left: 0;
        text-align: center;
        color: #ccc;
        cursor: default;
    }
    &-down-menu {
        border-top: 1px solid #ddd;
        text-align: right;
        padding: 5px 0;
        padding-right: 15px;
    }

    .color-cube {
        width: 12px;
        height: 12px;
        margin-right: 8px;
    }
    @mixin common-color {
        width: 12px;
        height: 12px;
        margin-right: 8px;
    }
    // 默认颜色
    .color- {
        background-color: #2d8cf0;
    }
    .color-ICblue {
        background-color: #2d8cf0;
    }
    .color-ICred {
        background-color: #ed4014;
    }
    .color-ICching {
        background-color: #2fbdb3;
    }
    .color-ICorange {
        background-color: #ff9900;
    }
    .color-ICgreen {
        background-color: #19be6b;
    }
    .color-ICpurple {
        background-color: #b60cea;
    }
    .color-ICpink {
        background-color: #ffa2d3;
    }
}
</style>
<style lang="scss">
.modal-label-select {
    .label-select-modal-content {
        .label-select-down-item-text {
            max-width: 160px;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .modal-color-cube {
            width: 12px;
            height: 12px;
            margin-right: 8px;
        }
    }
}
</style>